<?php
/**
 * Created by PhpStorm.
 * User: xiaomeng
 * Date: 17-8-31
 * Time: 下午12:10
 */
namespace swf\core;

use swf\socket\Response;
class App
{
    static private $allow_params = ['cmd','data'];
    static public function run($server, $frame)
    {
            //解析参数
            $data = self::parse($frame->data);

            if($data === false)
            {
                Response::send($server,$frame->fd,'error',[],1);

            } else {
                //1.分析路由
                $router = Router::check($data['cmd']);
                if($router === false)
                {
                    Response::send($server,$frame->fd,'error',[],2);
                } else {
                    //2.根据路由实例化控制器 将请求参数绑定到控制器 响应
                    $c = "\\app\\websocket\\controller\\".$router['controller'];
                    $a = $router['method'];
                    if(!class_exists($c))
                    {
                        Response::send($server,$frame->fd,'error',[],3);
                    }
                    $nc = new $c();
                    if(!method_exists($nc,$a))
                    {
                        Response::send($server,$frame->fd,'error',[],3);
                    }
                    $nc->init($server,$frame,$data);
                    $nc->$a();
                }
            }



    }

    /**
     * 解析参数
     * @param string $reqData
     * @return mixed
     */
    static public function parse($reqData = "")
    {
        $data = json_decode($reqData,true);
        //过滤参数
        $data = Filter::escape($data);
        if(!is_array($data))
        {
            return false;
        }
        //判断参数
        $_res = self::checkParam($data);
        if($_res === false)
        {
            return false;
        }

        return $data;
    }

    /**
     * 判断必须参数是否存在
     * @param $data
     * @return bool
     */
    static public function checkParam($data)
    {
        foreach (self::$allow_params as $v)
        {
            if(!array_key_exists($v,$data))
            {
                return false;
            }
        }
    }


}